const fs = require('fs');
const path = require('path');
const sdk = require('@baiducloud/sdk');
const BosClient = sdk.BosClient;

function getEnvFiles(dir) {
    let envFiles = [];
    const items = fs.readdirSync(dir);

    items.forEach((item) => {
        const fullPath = path.join(dir, item);

        const stat = fs.statSync(fullPath);
        if ((stat.isFile() && item.endsWith('.txt')) || (stat.isFile() && item.endsWith('.json'))) {
            envFiles.push(fullPath);
        } else if (stat.isDirectory()) {
            envFiles = envFiles.concat(getEnvFiles(fullPath));
        }
    });

    return envFiles;
}

// BOS相关的处理函数
const config = {
    endpoint: 'http://bd.bcebos.com',
    credentials: {
        ak: '6356708ce8d342bf965f2047d7c3cdb2',
        sk: 'd4837f696fdf4cf4abf11a80a1067abb'
    }
};

// BOS相关操作
const bucket = 'label-anything';
const client = new BosClient(config);
async function uploadFileToBOS(localFilePath, remoteFileName) {
    try {
        const response = await client.putObjectFromFile(bucket, remoteFileName, localFilePath);
        // console.log(`${remoteFileName} uploaded successfully`);
        return response;
    } catch (error) {
        console.error(`Failed to upload ${remoteFileName}:`, error);
        throw error;
    }
}
// 主函数
async function main() {
    // 读取当前目录下的conda目录
    let conda_envs_dir = path.join(__dirname, 'conda');
    let env_files = getEnvFiles(conda_envs_dir);
    let env_list = env_files.map((item) => {
        return path.basename(item);
    });
    // console.log(env_files);
    // console.log(env_list);

    // 上传配置文件到对应的BOS目录下
    let bos_base_path = '/labelapp/conda/';
    for (let i = 0; i < env_files.length; i++) {
        let env_file = env_files[i];
        let remote_path = `${bos_base_path}${env_list[i]}`;
        console.log(`upload ${env_file} => ${remote_path}`);
        await uploadFileToBOS(env_file, remote_path);
    }

    // 上传列表到BOS
    // let env_list_path = path.join(__dirname, 'conda', 'env.list');
    // let remote_list_path = '/labelapp/conda/env.list';
    // fs.writeFileSync(env_list_path, env_list.join('\n'));
    // await uploadFileToBOS(env_list_path, remote_list_path);
    // fs.unlinkSync(env_list_path);
}

main();
